package com.orion.app.controller;

import com.orion.app.domain.entity.EmployeeContactDetail;
import com.orion.app.domain.entity.EmployeeDetails;
import com.orion.app.domain.entity.PanStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/employeecontactdetails")
@Controller
@RooWebScaffold(path = "employeecontactdetails", formBackingObject = EmployeeContactDetail.class)
public class EmployeeContactDetailController {
    private static final Log log = LogFactory.getLog(EmployeeContactDetailController.class);
    @InitBinder
    protected void 	initBinder(HttpServletRequest request,
                                  ServletRequestDataBinder binder)
            throws ServletException {
        // Convert multipart object to byte[]
        binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
    }

    String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {}
        return pathSegment;
    }

    void populateEditForm(Model uiModel, EmployeeContactDetail employeeContactDetail) {
        uiModel.addAttribute("employeeContactDetail", employeeContactDetail);
        uiModel.addAttribute("employeedetailses", EmployeeDetails.findAllEmployeeDetailses());
        uiModel.addAttribute("panstatuses", PanStatus.findAllPanStatuses());
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        EmployeeContactDetail employeeContactDetail = EmployeeContactDetail.findEmployeeContactDetail(id);
        employeeContactDetail.remove();
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/employeecontactdetails";
    }

    @RequestMapping(value = "/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("id") Long id, Model uiModel) {
        populateEditForm(uiModel, EmployeeContactDetail.findEmployeeContactDetail(id));
        return "employeecontactdetails/update";
    }

    @RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid EmployeeContactDetail employeeContactDetail, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, employeeContactDetail);
            return "employeecontactdetails/update";
        }
        uiModel.asMap().clear();
        employeeContactDetail.merge();
        return "redirect:/employeecontactdetails/" + encodeUrlPathSegment(employeeContactDetail.getId().toString(), httpServletRequest);
    }

    @RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("employeecontactdetails", EmployeeContactDetail.findEmployeeContactDetailEntries(firstResult, sizeNo));
            float nrOfPages = (float) EmployeeContactDetail.countEmployeeContactDetails() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("employeecontactdetails", EmployeeContactDetail.findAllEmployeeContactDetails());
        }
        return "employeecontactdetails/list";
    }

    @RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Long id, Model uiModel) {
        uiModel.addAttribute("employeecontactdetail", EmployeeContactDetail.findEmployeeContactDetail(id));
        uiModel.addAttribute("itemId", id);
        return "employeecontactdetails/show";
    }

    @RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel) {
        populateEditForm(uiModel, new EmployeeContactDetail());
        List<String[]> dependencies = new ArrayList<String[]>();
        if (EmployeeDetails.countEmployeeDetailses() == 0) {
            dependencies.add(new String[] { "employeedetails", "employeedetailses" });
        }
        if (PanStatus.countPanStatuses() == 0) {
            dependencies.add(new String[] { "panstatus", "panstatuses" });
        }
        uiModel.addAttribute("dependencies", dependencies);
        return "employeecontactdetails/create";
    }

    @RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid EmployeeContactDetail employeeContactDetail,
                         @RequestParam("employeePhoto") MultipartFile employeePhoto, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
        log.info("Document: ");
        log.info("Name: "+employeePhoto.getOriginalFilename());
        log.info("File: " +employeePhoto.getName());
        log.info("Type: "+employeePhoto.getContentType());
        log.info("Size: "+employeePhoto.getSize());


        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, employeeContactDetail);
            return "employeecontactdetails/create";
        }
        uiModel.asMap().clear();
        employeeContactDetail.persist();
        return "redirect:/employeecontactdetails/" + encodeUrlPathSegment(employeeContactDetail.getId().toString(), httpServletRequest);
    }
}
